package com.smh.a01dianmingqiDemo1;

import java.io.*;
import java.util.ArrayList;
import java.util.Collections;

public class Test4 {
    public static void main(String[] args) throws IOException {
//随机点名器4 (学生独立完成)
//需求:
//一个文件里面存储了班级同学的姓名，每一个姓名占一行，要求通过程序实现随机点名器。
//运行效果:
//被点到的学生不会再被点到
//如果班级中所有的学生都点完了，需要自动的重新开启第二轮点名
//细节1:假设班级有10个学生，每一轮中每一位学生只能被点到一次，程序运行10次，第一轮结束
//细节2:第11次运行的时候，我们自己不需要手动操作本地文件，要求程序自动开始第二轮点会

        File file = new File("day28-code\\file\\names.txt");
        File file1 = new File("day28-code\\file\\names2.txt");
        File file2 = new File("day28-code\\file\\count2.txt");
        BufferedReader brCount = new BufferedReader(new FileReader(file2));
        String count = brCount.readLine();
        brCount.close();
        int c = Integer.parseInt(count);
        if (c / 10 % 2 == 0) {

        } else {
            File temp = file;
            file = file1;
            file1 = temp;
        }
        //获取数据
        BufferedReader br = new BufferedReader(new FileReader(file));
        ArrayList<String> nameList = new ArrayList<>();
        String s;
        while ((s = br.readLine()) != null) {
            nameList.add(s);
        }
        br.close();
        //打乱,随机出一个
        Collections.shuffle(nameList);
        String s1 = nameList.get(0).split("-")[0];
        System.out.println(s1);
        //创建新的集合
        //读取数据
        ArrayList<String> newNameList = new ArrayList<>();
        BufferedReader newbr = new BufferedReader(new FileReader(file1));
        while ((s = newbr.readLine()) != null) {
            newNameList.add(s);
        }
        newbr.close();

        //将选中的学生加入新集合
        newNameList.add(nameList.get(0));
        //将选中的学生从原集合中删除
        nameList.remove(0);
        //将原集合中的数据写回文件
        BufferedWriter bw = new BufferedWriter(new FileWriter(file));
        for (String s2 : nameList) {
            bw.write(s2);
            bw.newLine();
        }
        bw.close();
        //将新集合中的数据写回文件
        BufferedWriter newbw = new BufferedWriter(new FileWriter(file1));
        for (String s2 : newNameList) {
            newbw.write(s2);
            newbw.newLine();
        }
        newbw.close();

        //次数加以写回
        BufferedWriter bwCount = new BufferedWriter(new FileWriter(file2));
        bwCount.write(String.valueOf(c + 1));
        bwCount.close();

    }
}
